//
//  NSString+Extension.m
//  微blog
//
//  Created by Jorn.Wu on 15/8/29.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "NSString+Extension.h"
#import "RegexKitLite.h"

@implementation NSString (Extension)

+ (instancetype)stringWithString:(NSString *)string handleByRegex:(NSString *)regexStr{
    
    /**
     * e.g. ---》 解析表情图片 :[兔子] ---> <image url = '001.png'>
     */
    
    //    2、查找到表情 ---> [兔子]
    NSArray *faceItem = [string componentsMatchedByRegex:regexStr];
    //    3、添加配置文件，用于查找对应的名字
    NSString *configPath = [[NSBundle mainBundle] pathForResource:@"emoticons" ofType:@"plist"];
    NSArray *faceConfigAr = [NSArray arrayWithContentsOfFile:configPath];
    
    for (NSString *faceName in faceItem) {
        //    4、编写key通过谓词过滤，找出对应的字典（表情的配置信息）
        NSString *str = [NSString stringWithFormat:@"self.chs='%@'",faceName];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
        NSArray *items = [faceConfigAr filteredArrayUsingPredicate:predicate];
        
        if (items.count != 0) {         //如果找到了
            NSDictionary *faceDic = items[0];       //其实只有对应的一个
            NSString *imageName = [faceDic objectForKeyedSubscript:@"png"];         //取出配置文件中对应的名字
            NSString *repalceStr = [NSString stringWithFormat:@"<image url = '%@'>",imageName];         //编写用于替换的字符串
            string = [string stringByReplacingOccurrencesOfString:faceName withString:repalceStr];        //替换微博中的表情【转为表情连接】<image url = '001.png'>
        }
    }
    
    return string;
    
}

+ (instancetype)stringByEmotionRegexHandleFromString:(NSString *)string{
    //    1、编写正则表达式
    NSString *regex = @"\\[\\w+\\]";
    
    NSString *newStr = [self stringWithString:string handleByRegex:regex];
    
    return newStr;
}

@end









